package com.mega.fe.util.klass;

import com.mega.fe.util.MEGA;
import net.minecraftforge.fml.loading.moddiscovery.AbstractJarFileDependencyLocator;
import org.apache.commons.io.FileUtils;
import org.lwjgl.glfw.GLFW;
import com.mega.fe.asm.*;

import javax.management.MXBean;
import java.io.File;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;

public class InstManager {
    public static Instrumentation inst;
    public static ClassLoader BOOT_LOADER;

    static {
        try {
            Class<?> klass = Class.forName("jdk.internal.loader.ClassLoaders");
            Field f2 = klass.getDeclaredField("BOOT_LOADER");
            MEGA.setAccessible(f2, true);
            BOOT_LOADER = (ClassLoader) f2.get(null);
        } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void agentmain(String args, Instrumentation inst) throws ClassNotFoundException {
        System.out.println(InstManager.class.getClassLoader());
        InstManager.inst = inst;
        System.out.println(MEGA.class.getResource("") );
        System.out.println("-|-----------M Y T H-----------|-");
        System.out.println("-|     The MegaAgent start.    |-");
        System.out.println("-|-----------M E G A-----------|-");
        Thread.currentThread().getContextClassLoader().loadClass("com.mega.fe.util.klass.EventUtil");
        inst.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
                //System.out.println("-|-MegaAgent: transform class:"+className);
                if (className.startsWith("com/mega") || className.startsWith("com.mega"))  {
                    return ClassFileTransformer.super.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);

                }

                if (className.equals("org/lwjgl/glfw/GLFW")) {
                    //System.exit(0);
                    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
                    ClassReader classReader = new ClassReader(classfileBuffer);
                    ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM7, classWriter) {
                        @Override
                        public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                            if (name.equals("glfwSetWindowTitle") && descriptor.equals("(JLjava/lang/CharSequence;)V")) {
                                return null;
                            }

                            return super.visitMethod(access, name, descriptor, signature, exceptions);

                        }

                        @Override
                        public void visitEnd() {
                            MethodVisitor mv = cv.visitMethod(Modifier.PUBLIC | Modifier.STATIC, "glfwSetWindowTitle", "(JLjava/lang/CharSequence;)V", null, null);
                            mv.visitCode();
                            mv.visitMethodInsn(Opcodes.INVOKESTATIC
                                    , "com/mega/fe/util/klass/EventUtil"
                                    , "glfwSetWindowTitle"
                                    , "()V"
                                    ,false);
                            mv.visitInsn(Opcodes.RETURN);
                            mv.visitMaxs(3, 3);
                            super.visitEnd();
                        }
                    };
                    classReader.accept(classVisitor, 0);
                    byte[] bytes = classWriter.toByteArray();
                    try {
                        FileUtils.writeByteArrayToFile(new File("C:\\Users\\HP1\\Desktop\\az.txt"), bytes.clone());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return bytes;
                }

                return null;
                }
        }, true);
        try {
            MEGA.IMPL_LOOKUP().ensureInitialized(EventUtil.class);
            PathSetter.init();
         } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public static ClassLoader agentClassLoader() {
        return InstManager.class.getClassLoader();
    }

    public static Instrumentation getInstrumentation() {
        return inst;
    }
}


